package com.itfenghuang.controller;

import com.github.pagehelper.PageInfo;
import com.itfenghuang.domain.User;
import com.itfenghuang.dto.UserDto;
import com.itfenghuang.service.UserService;

import com.itfenghuang.util.*;
import com.itfenghuang.vo.PageVo;
import com.itfenghuang.vo.SelectVo;
import com.itfenghuang.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
//@CrossOrigin//解决跨域的注解
@RequestMapping("user")
public class UserController {



    //引入Service
    @Resource
    UserService userService;
    //1.注册
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody UserVo userVo){
        User userDB= userService.selectOne(userVo.getUsername());
        //判断账号是否存在,为空代表账号不存在
        if (ObjectUtils.isEmpty(userDB)){
            //获取redis中的验证码进行对比
            String  rediscode= (String) redisTemplate.opsForValue().get(userVo.getPhone());
            //判断验证码是否为空
            if (!ObjectUtils.isEmpty(rediscode)) {
                //验证码不为空,则对比前端传入和redis存的验证码
                if (userVo.getCode().toString().equals(rediscode)) {
                    //验证码比对相同则成功注册
                    User user = new User();
                    //将userVo的数据复制到user中
                    BeanUtils.copyProperties(userVo,user);
                    userService.register(user);
                    return new Result(true,200,"注册成功");
                } else {
                    //验证码输入错误,即对比错误
                    return new Result(false, 205, "验证码错误");
                }
            }else {
                //验证码为空,重新校验验证码
                return new Result(false,204,"验证码失效");
            }
        }else {
            //账号不为空,则代表账号存在
            return new Result(false,206,"该账号存在");
        }

    }

    //使用redisTemplate模板
    @Resource
    RedisTemplate redisTemplate;

    //2.短信验证码
    @GetMapping("sendcode")
    @ResponseBody
    public Result sendcode(String phone){
        //将短信验证码存入redis中,注册的时候从redis中获取验证码进行验证
        //调用短信接口
        SendCode sendCode = new SendCode();
        Integer mobile_code = sendCode.sendCode(phone);
        System.out.println(mobile_code);
        //60秒之后数据自动清除
        redisTemplate.opsForValue().set(phone,mobile_code+"",9000, TimeUnit.SECONDS);
        return new Result(true,200,"验证码发送成功");
    }


    //3.登录
    @GetMapping("login")
    @ResponseBody
    public Result login(User user){
        //1.通过用户名查询该用户名是否存在
        User userDB = userService.selectOne(user.getUsername());
        if (!ObjectUtils.isEmpty(userDB)){
            //不为空,则对比密码
            if (user.getPassword().equals(userDB.getPassword())){
                //拦截验证,传一个 token,传递给前端
                HashMap<String, Object> map = new HashMap<>();
                map.put("user",user.getUsername());
                String token = JwtUtil.createToken(map);
                //将整个userdto对象返回给前端,包含token
                UserDto userDto = new UserDto();
                userDto.setToken(token);
                //将user中的数据复制到userdto中
                BeanUtils.copyProperties(userDB,userDto);
                return new Result(true,200,"登录成功",userDto);
            }else {
                //密码不正确
                return new Result(false,202,"密码错误");
            }
        }else {
            //用户名为空
        }
        return new Result(false,201,"该账号不存在");
    }

    //4.分页查询所有数据
    @PostMapping("/selectAllUser")
    @ResponseBody
    public Result selectAllUser(@RequestBody PageVo pageVo){
        //返回pageinfo分页插件
        PageInfo<User> all= userService.selectAll(pageVo);
        return new Result(true,200,"查询成功",all);
    }

    //5.根据条件查询数据
    @PostMapping("/selectByUser")
    @ResponseBody
    public Result selectByUser(@RequestBody SelectVo selectVo){
        PageInfo<User>  all=userService.selectByUser(selectVo);
        return new Result(true,200,"查询成功",all);
    }

    //6.根据勾选删除数据
    @PostMapping("/deleteByIds")
    @ResponseBody
    public Result deleteByIds(@RequestBody List<Integer> ids){
        userService.deleteByIds(ids);
        return new Result(true,200,"查询成功");
    }


    //7.导出勾选用户,导出报表
    @PostMapping("/exportUserinfo")
    @ResponseBody
    public Result exportUserinfo(@RequestBody List<Integer> ids, HttpServletResponse response) throws Exception {
        List<User>  list=userService.exportUserinfo(ids);
        ExportUser exportUser = new ExportUser();
        String s = exportUser.exportUser(list, response);
        return new Result(true,200,"导出成功",s);
    }

    //8.导出全部勾选用户
    @GetMapping("/exportAllUserinfo")
    @ResponseBody
    public Result exportAllUserinfo(HttpServletResponse response) throws Exception {
        List<User> list=userService.exportAllUserinfo();
        ExportUser exportUser = new ExportUser();
        String s = exportUser.exportUser(list, response);
        return new Result(true,200,"导出成功",s);
    }

    //9.上传头像
    @RequestMapping("upload")
    @ResponseBody
    public Result upload(MultipartFile upload) throws IOException {
        //1.获取上传的文件原始名
        String originalFilename = upload.getOriginalFilename();
        System.out.println(originalFilename);
        //2.获取该文件的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.重命名该文件  -代替成空串
        String uuid = UUID.randomUUID().toString().replace("-", "");
        long mills = System.currentTimeMillis();
        //4.拼接新名字
        String newName=uuid+mills+substring;
        //5.开始上传
        OssClient ossClient = new OssClient();
        String url = ossClient.uploadfile(newName, "lvdolv", upload.getInputStream());
        return new Result(true,200,"上传头像成功",url);
    }


    //10.修改用户信息
    @PostMapping("updateUser")
    @ResponseBody
    public Result updateUser(@RequestBody User user){
        userService.updateUser(user);
        return new Result(true,200,"修改成功");
    }

}
